package com.hhu.userservice.service.imp;

import com.hhu.userservice.dao.TeacherInfoMapper;
import com.hhu.userservice.object.dto.TeacherInfo;
import com.hhu.userservice.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeacherServiceImp implements TeacherService {

    //todo：由于现在没有获取当前用户的信息，所以权限暂时没做，以后可以补上

    private TeacherInfoMapper teacherInfoMapper;

    @Autowired
    public void setTeacherInfoMapper(TeacherInfoMapper teacherInfoMapper) {
        this.teacherInfoMapper = teacherInfoMapper;
    }

    @Override
    public List<TeacherInfo> queryAllTeachers() {
        return teacherInfoMapper.getAllTeacher();
    }

    @Override
    @Transactional
    public void addTeachers(List<TeacherInfo> teacherInfos) {

        // 检查注册id的唯一性
        HashSet<String> set = new HashSet();
        for (TeacherInfo teacherInfo : teacherInfos) {
            if(!set.add(teacherInfo.getUserId())) throw new RuntimeException("用户注册账号不能重复！");
        }

        List<TeacherInfo> existedList = teacherInfoMapper.queryTeachersByUserId(teacherInfos);

        if (!CollectionUtils.isEmpty(existedList)) {
            String existedUserIdList = existedList.stream().map(o -> o.getUserId()).collect(Collectors.joining("\n"));
            throw new RuntimeException("以下用户id已被注册\n：" + existedUserIdList);
        }
        // 添加到用户表
        teacherInfoMapper.insertTeacherInfos(teacherInfos);
        // 添加到用户——角色表，自动为该用户添加为教师角色
        String teacherRoleId = "2"; // 这里为了方便，先固定为2（数据库中教师角色的id为2），以后写Role的相关接口时再把这里改了。
        teacherInfos.forEach(o -> o.setRoleId(teacherRoleId));
        teacherInfoMapper.insertTeacherUserRole(teacherInfos);
    }


    /**
     * 批量删除教师
     * @param teacherInfos
     */
    @Override
    public void deleteTeachers(List<TeacherInfo> teacherInfos) {

        teacherInfoMapper.deleteTeacherInfos(teacherInfos);

        teacherInfoMapper.deleteTeacherUserRole(teacherInfos);

    }


    /**
     * 单笔更新教师信息
     * @param teacherInfo
     */
    @Override
    public void updateTeacher(TeacherInfo teacherInfo) {

        teacherInfoMapper.updateTeacherInfo(teacherInfo);

    }
}
